﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Stock
{	public partial class WriteOff : Form
	{	private	Util.ActionType actionType;
		private	WriteOffs writeOffs;
//-------------------------------------------------------------------------------------------------
		private	DIProject.DataSets.Stock writeOffsStock{get{return writeOffs != null? writeOffs.stock: null;}}
		private	DIProject.DataSets.StockTableAdapters.WriteOffsTableAdapter writeOffsTableAdapter{get{return writeOffs != null? writeOffs.writeOffsTableAdapter: null;}}
		private	DIProject.DataSets.Stock.WriteOffsRow writeOffsRow = null;
		private	int docId{get{return writeOffsRow != null? writeOffsRow.Id: 0;}}
		private	string docNumber{get{return writeOffsRow != null? writeOffsRow.DocNumber: Properties.Resources.strUndefined;}}
		private	string docDate{get{return writeOffsRow != null? writeOffsRow.DocDate.ToString("d"): Properties.Resources.strUndefined;}}
		private decimal sum
		{	get
			{	object s = stock.WriteOffLines.Compute("sum(RetailSum)", null);
				return s is decimal? (decimal)s: 0m;
			}
		}
//-------------------------------------------------------------------------------------------------
		public WriteOff() : this(Util.ActionType.NoAction, null)
		{
		}

		public WriteOff(Util.ActionType actionType, WriteOffs writeOffs)
		{	
            InitializeComponent();
			textFormat = Text;
			this.actionType	= actionType;
			this.writeOffs	= writeOffs;
			toolStripButtonUpdate.Enabled = false;
			toolStripButtonDelete.Enabled = false;
			if(	actionType == DIProject.Util.ActionType.Update
			&&	writeOffs != null
			&&	writeOffs.writeOffsGridView.CurrentCell != null)
				writeOffsRow = (DIProject.DataSets.Stock.WriteOffsRow)((DataRowView)writeOffs.writeOffsGridView.CurrentCell.OwningRow.DataBoundItem).Row;
		}
//-------------------------------------------------------------------------------------------------
		private readonly string textFormat;
		private void SetCaption()
		{	Text = string.Format
			(	textFormat
			,	docNumber
			,	docDate
			,	sum.ToString("N2")
			);
		}
//-------------------------------------------------------------------------------------------------
		private void WriteOff_Load(object sender, EventArgs e)
		{	try
			{	switch(actionType)
				{	case DIProject.Util.ActionType.Insert:
						writeOffsRow = writeOffsStock.WriteOffs.NewWriteOffsRow();
						writeOffsRow.DocDate	= DateTime.Today;
						writeOffsRow.MD			= DateTime.Now;
						writeOffsRow.MW			= FirstForm.Login;
						writeOffsStock.WriteOffs.AddWriteOffsRow(writeOffsRow);
						goto case DIProject.Util.ActionType.Update;
					case DIProject.Util.ActionType.Update:
						writeOffLinesTableAdapter.Fill(stock.WriteOffLines, docId);
						textBoxNote.DataBindings.Add("Text", writeOffsRow, "Note");
						break;
				}
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
		private void WriteOff_FormClosed(object sender, FormClosedEventArgs e)
		{	try
			{	if(DialogResult == DialogResult.OK)
				{	int		delLines = stock.WriteOffLines.Select(null, null, DataViewRowState.Deleted	).Length
						,	insLines = stock.WriteOffLines.Select(null, null, DataViewRowState.Added	).Length
						;
					writeOffsTableAdapter.Update(writeOffsRow);				// Заголовок документа
					if(actionType == DIProject.Util.ActionType.Insert)
					{	writeOffs.writeOffsGridView.CurrentCell = writeOffs.writeOffsGridView.Rows[writeOffs.writeOffsGridView.Rows.Count - 1].Cells[writeOffs.writeOffsGridView.CurrentCell.ColumnIndex];
						for(int i = 0, n = stock.WriteOffLines.Rows.Count; i < n; ++i)
							stock.WriteOffLines[i].DocId = writeOffsRow.Id;
					}
					writeOffLinesTableAdapter.Update(stock.WriteOffLines);	// Строки документа
					writeOffsRow.Lines	= writeOffsRow.Lines - delLines + insLines;
					writeOffsRow.DocSum	= sum;

					writeOffsRow.AcceptChanges();
					stock.WriteOffLines.AcceptChanges();
				}
				else
				{	writeOffsRow.RejectChanges();
					stock.WriteOffLines.RejectChanges();
				}
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
//-------------------------------------------------------------------------------------------------
		private void WriteOff_Resize(object sender, EventArgs e)
		{	textBoxNote.Width = panelHeader.ClientSize.Width - labelNote.Left - textBoxNote.Left;
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
		{	if(clickedCell != null)
			{	updateToolStripMenuItem.Enabled = true;
				deleteToolStripMenuItem.Enabled = true;
			}
			else
			{	updateToolStripMenuItem.Enabled = false;
				deleteToolStripMenuItem.Enabled = false;
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private DataGridViewCell clickedCell = null;
		private void linesGridView_MouseDown(object sender, MouseEventArgs e)
		{	clickedCell = null;
			if(e.Button == MouseButtons.Right)
			{	DataGridView.HitTestInfo hit = linesGridView.HitTest(e.X, e.Y);
				if(hit.Type == DataGridViewHitTestType.Cell)
					linesGridView.CurrentCell = clickedCell = linesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
			}
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_CurrentCellChanged(object sender, EventArgs e)
		{	if(linesGridView.CurrentCell != null)
			{	toolStripButtonUpdate.Enabled = true;
				toolStripButtonDelete.Enabled = true;
			}
			else
			{	toolStripButtonUpdate.Enabled = false;
				toolStripButtonDelete.Enabled = false;
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void toolStripRefresh_Click(object sender, EventArgs e)
		{	try
			{	writeOffLinesTableAdapter.Fill(stock.WriteOffLines, docId);
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripPrint_Click(object sender, EventArgs e)
		{	bool changed	= writeOffsRow.RowState != DataRowState.Unchanged
						||	DIProject.Util.Common.HasChanges(stock.WriteOffLines)
						;
			if(changed)
			{	if(MessageBox.Show
				(	this
				,	Properties.Resources.strDocIsChanged
				,	Properties.Resources.strConfirmation
				,	MessageBoxButtons.YesNo
				,	MessageBoxIcon.Question
				,	MessageBoxDefaultButton.Button1
				) == DialogResult.Yes)
				{	try
					{	writeOffLinesTableAdapter.Update(stock);
						changed = false;
					}
					catch(SqlException eq)
					{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
					catch(Exception ex)
					{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
			if(!changed)
			{	WriteOffRpt writeOffRpt = new WriteOffRpt(docId);
				writeOffRpt.ShowDialog(this);
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripInsert_Click(object sender, EventArgs e)
		{	WriteOffLine writeOffLine = new WriteOffLine(Util.ActionType.Insert);
			if(writeOffLine.ShowDialog(this) == DialogResult.OK)
			{	try
				{	DIProject.DataSets.Dictionary.PartiesRow partyRow = writeOffLine.PartyRow;
					DIProject.DataSets.Stock.WriteOffLinesRow newRow = stock.WriteOffLines.NewWriteOffLinesRow();
					newRow.DocId			= docId;
					newRow.PartyId			= partyRow.Id;
					newRow.Name				= partyRow.Name;
					newRow.ManufacturerId	= partyRow.ManufacturerId;
					newRow.ManufacturerName	= partyRow.ManufacturerName;
					newRow.RetailPrice		= partyRow.RetailPrice;
					newRow.Qntty			= writeOffLine.Qntty;
					newRow.RetailSum		= partyRow.RetailPrice*writeOffLine.Qntty;
					newRow.ReasonId			= writeOffLine.ReasonId;
					newRow.ReasonName		= writeOffLine.ReasonName;
					newRow.ReasonText		= writeOffLine.ReasonText;
					newRow.QualityLossMark	= writeOffLine.QualityLossMark;
				//?	newRow.ReturnLineId		= ;
					newRow.Note				= writeOffLine.Note;
					newRow.MD				= DateTime.Now;
					newRow.MW				= FirstForm.Login;
					stock.WriteOffLines.AddWriteOffLinesRow(newRow);
					linesGridView.CurrentCell = linesGridView.Rows[stock.WriteOffLines.Count - 1].Cells[linesGridView.CurrentCell.ColumnIndex];
				}
				catch(SqlException eq)
				{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				SetCaption();
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripUpdate_Click(object sender, EventArgs e)
		{	if(linesGridView.CurrentCell != null)
			{	try
				{	DIProject.DataSets.Stock.WriteOffLinesRow row = (DIProject.DataSets.Stock.WriteOffLinesRow)((DataRowView)linesGridView.CurrentCell.OwningRow.DataBoundItem).Row;
					WriteOffLine writeOffLine	= new WriteOffLine(Util.ActionType.Update);
					writeOffLine.Party			= row.PartyId;
					writeOffLine.Manufacturer	= row.ManufacturerName;
					writeOffLine.Qntty			= row.Qntty;
					writeOffLine.Price			= row.RetailPrice;
					writeOffLine.ReasonId		= row.ReasonId;
					writeOffLine.ReasonText		= row.ReasonText;
					writeOffLine.QualityLossMark= row.QualityLossMark;
					writeOffLine.Note			= row.Note;
					if(writeOffLine.ShowDialog(this) == DialogResult.OK)
					{	row.Qntty			= writeOffLine.Qntty;					// Меняются только количество
						row.RetailSum		= row.RetailPrice*writeOffLine.Qntty;	//   сумма
						row.ReasonId		= writeOffLine.ReasonId;				//   идентификатор причины
						row.ReasonName		= writeOffLine.ReasonName;				//   наименование причины
						row.ReasonText		= writeOffLine.ReasonText;				//   примечание к причине
						row.QualityLossMark	= writeOffLine.QualityLossMark;			//   признак понижения качества
						row.Note			= writeOffLine.Note;					//   и примечание
						SetCaption();
					}
				}
				catch(SqlException eq)
				{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripDelete_Click(object sender, EventArgs e)
		{	DIProject.DataSets.Stock.WriteOffLinesRow rowToDelete;
			if(	linesGridView.CurrentCell != null
			&&	(rowToDelete = (DIProject.DataSets.Stock.WriteOffLinesRow)((DataRowView)linesGridView.CurrentCell.OwningRow.DataBoundItem).Row) != null
			&&	MessageBox.Show
				(	this
				,	string.Format(Properties.Resources.strDeleteDocLine, rowToDelete.Name)
				,	Properties.Resources.strConfirmation
				,	MessageBoxButtons.YesNo
				,	MessageBoxIcon.Question
				,	MessageBoxDefaultButton.Button1
				) == DialogResult.Yes
			)
			{	try
				{	rowToDelete.Delete();
				}
				catch(SqlException eq)
				{	rowToDelete.RejectChanges();
					MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	rowToDelete.RejectChanges();
					MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				SetCaption();
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void linesGridView_KeyDown(object sender, KeyEventArgs e)
		{	if(e.KeyCode == Keys.Enter)
				e.Handled = true;
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_KeyPress(object sender, KeyPressEventArgs e)
		{	if(e.KeyChar == '\r' && linesGridView.CurrentCell != null)
				toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_MouseDoubleClick(object sender, MouseEventArgs e)
		{	DataGridView.HitTestInfo hit = linesGridView.HitTest(e.X, e.Y);
			if(hit.Type == DataGridViewHitTestType.Cell)
			{	linesGridView.CurrentCell = clickedCell = linesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
				toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
	}
}